package com.example.mq.mqserver;

import com.example.mq.common.*;
import com.example.mq.mqserver.core.BasicProperties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 消息队列的本体服务器
public class BrokerServer {
    private ServerSocket serverSocket = null;
    // 当前考虑一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    // 使用哈希表表示当前的所有会话
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    private ExecutorService executorService = null;
    private volatile boolean runnable = true;
    public BrokerServer(int port) throws Exception {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("BrokerServer is starting...");
        executorService = Executors.newCachedThreadPool();
        try{
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                // 把处理连接的逻辑丢给线程池
                executorService.submit(()->{
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("BrokerServer 服务器停止运行");
        }
    }

    // 停止服务器，就是直接杀掉对应的进程
    public void stop() throws IOException {
        runnable = false;
        // 线程池中任务都放弃，让线程都销毁
        executorService.shutdownNow();
        // 关闭serverSocket
        serverSocket.close();
    }

    // 处理一个客户端的连接
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 按照特定格式读取并解析
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while(true) {
                    // 1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    // 2.根据请求计算响应
                    Response response = process(request,clientSocket);
                    // 3.响应写回给客户端
                    writeResponse(dataOutputStream,response);
                }
            }
        } catch (EOFException | SocketException e) {
            // DataInputStream.readUTF()方法读取到流的末尾，抛出EOFException异常
            // 需要借助它进行结束
            System.out.println("[BrokerServer] clientSocket closed! 客户端地址"+clientSocket.getInetAddress().toString() +
                    "端口号"+clientSocket.getPort());
        }
        catch (IOException | ClassNotFoundException | MqException e) {
            e.printStackTrace();
            System.out.println("[BrokerServer] connection 出现异常");
        } finally {
            try {
                clientSocket.close();
                // 一个TCP连接可能包含多个channel,需要把当前这个socket对应的channel也顺便清理
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void clearClosedSession(Socket clientSocket) {
        // 遍历session hash表
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if(entry.getValue() == clientSocket){
                // 不能一边遍历一边删除
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理 session 完成! 被清理的 channelId=" + toDeleteChannelId);
    }

    // 响应写回到客户端
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        // 刷新缓冲区
        dataOutputStream.flush();
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1.把request 中的 payload
        BasicArguments basicArguments =(BasicArguments) BinaryTool.toObject(request.getPayload());
        System.out.println("[Request] rid=" + basicArguments.getRid() + ", channelId=" + basicArguments.getChannelId()
                + ", type=" + request.getType() + ", length=" + request.getLength());
        // 2.根据request中的type，调用不同的方法处理
        boolean ok = true;
        if (request.getType() == 0x1) {
            // 创建 channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建 channelId=" + basicArguments.getChannelId() + " 成功");
        }else if (request.getType() == 0x2) {
            // 关闭 channel
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 关闭 channelId=" + basicArguments.getChannelId() + " 成功");
        } else if (request.getType() == 0x3) {
            // 创建交换机，此时payload 就是 ExchangeArguments 对象
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x4) {
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(),
                    arguments.isExclusive(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.deleteQueue(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(),
                    arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(),
                    arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        // 它就是把服务器收到的消息可以直接推送到对应的消费者客户端
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            // consumerTag 是 channelI，根据 channelId 去 session 查询，就可以得到对应的socket对象，从而就可以发数据
                            // 1.根据channelId获取socket
                            Socket client = sessions.get(consumerTag);
                            if(clientSocket == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokerServer] client is closed");
                            }
                            // 2. 构造响应数据
                            SubScribeReturns subScribeReturns = new SubScribeReturns();
                            subScribeReturns.setChannelId(consumerTag);
                            subScribeReturns.setRid(""); // 这里只有响应，没有请求，不需要对应，rid暂时不需要
                            subScribeReturns.setOk(true);
                            subScribeReturns.setConsumerTag(consumerTag);
                            subScribeReturns.setBasicProperties(basicProperties);
                            subScribeReturns.setBody(body);
                            byte[] payload = BinaryTool.toBytes(subScribeReturns);
                            Response response = new Response();
                            // 0xc 表示服务器给消费者客户端推送的数据
                            response.setType(0xc);
                            // response 的 payload 是一个 SubScribeReturns
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            // 3. 把数据写入客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            // 调用 basicAck 确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(),arguments.getMessageId());
        } else {
            // 当前 type 是非法的
            throw new MqException("[BrokerServer] 非法请求类型: " + request.getType());
        }
        // 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid="+ basicReturns.getRid() + ", channelId=" + basicArguments.getChannelId()
        + ", type=" + request.getType() + ", length=" + payload.length);
        return response;
    }

    // 构造request对象
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if(n != request.getLength()){
            throw new IOException("read request error");
        }
        request.setPayload(payload);
        return request;
    }
}
